package com.booking;

import java.util.Calendar;

import android.app.Application;
import android.content.res.Resources;

import com.booking.cacher.ImageCache;
import com.booking.cacher.ImageCache.ImageCacheParams;
import com.booking.cacher.ImageFetcher;
import com.booking.utils.PreferenceHelper;

/**
 * @author iholub May 22, 2013
 */
public class BookingApplication extends Application implements ImageFetchable {
	private static final float SIZE_OF_CACHE = 0.25f;
	private static final String IMAGE_CACHER_DIR_NAME = "images";
	private ImageCache mImageCache;
	private ImageFetcher mPlacePhotoFetcher;

	@Override
	public void onCreate() {
		super.onCreate();
		initImageFetchers();
	}

	@Override
	public ImageFetcher getPlacePhotoFetcher() {
		return mPlacePhotoFetcher;
	}

	@Override
	public ImageCache getImageCache() {
		return mImageCache;
	}

	@Override
	public void clearCache() {
		mPlacePhotoFetcher.clearCache();
	}

	protected void initImageFetchers() {
		ImageCacheParams cacheParams = new ImageCacheParams(
				getApplicationContext(), IMAGE_CACHER_DIR_NAME);
		cacheParams.setMemCacheSizePercent(getApplicationContext(),
				SIZE_OF_CACHE);
		Resources resources = getResources();
		mImageCache = new ImageCache(cacheParams);

		mPlacePhotoFetcher = new ImageFetcher(getApplicationContext(),
				(int) resources.getDimension(R.dimen.place_photo_width),
				(int) resources.getDimension(R.dimen.place_photo_height));
		mPlacePhotoFetcher.setImageCache(mImageCache);
		mPlacePhotoFetcher.initDiskCache();

		long time = PreferenceHelper
				.getCacheClearingTime(getApplicationContext());
		if (time == 0) {
			clearCache();
			PreferenceHelper.setCacheClearingTime(getApplicationContext(),
					System.currentTimeMillis());
		} else {
			Calendar date = Calendar.getInstance();
			Calendar lastClearing = Calendar.getInstance();
			lastClearing.setTimeInMillis(time);
			if (date.get(Calendar.DAY_OF_YEAR) != lastClearing
					.get(Calendar.DAY_OF_YEAR)
					|| date.get(Calendar.YEAR) != lastClearing
							.get(Calendar.YEAR)) {
				clearCache();
				PreferenceHelper.setCacheClearingTime(getApplicationContext(),
						System.currentTimeMillis());
			}
		}
	}

}
